package com.azunitech.apm;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;

import roboguice.activity.RoboActivity;

import com.azunitech.apm.common.api.IEventProxyService;
import com.azunitech.apm.common.api.Report;
import com.azunitech.apm.messages.Actions;
import com.azunitech.apm.osgi.AndroidBundleProvider;
import com.azunitech.apm.osgi.FileOperations;
import com.azunitech.apm.osgi.OSGiFramework;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HelloAndroidActivity extends RoboActivity {
	private static final String TAG = HelloAndroidActivity.class.getSimpleName();

	private OSGiFramework m_OSGiFramework;
	private ArrayList<String> m_DisplayList;
	private static final String KEY_BUNDLES_VALUE = "bundles";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        m_DisplayList = new ArrayList<String>();
        final TextView tv = (TextView) this.findViewById(R.id.textView1);
        
        Button btnStart = (Button) this.findViewById(R.id.btn_start);
        btnStart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
			    FileOperations.reportDirectoryPaths(HelloAndroidActivity.this);
			    File cacheDir = getCacheDir();
		        File baseDir = new File(cacheDir, "felix");
		        
		        m_DisplayList.clear();
		        m_DisplayList.add(baseDir.getAbsolutePath() + "\n");
		        
		        m_OSGiFramework = new OSGiFramework(baseDir, new AndroidBundleProvider(HelloAndroidActivity.this));
		        try {
		        	m_OSGiFramework.start();
					BundleContext context = m_OSGiFramework.getSystemContext();
					org.osgi.framework.Bundle[] bundles = context.getBundles();
					for( org.osgi.framework.Bundle b : bundles){
						m_DisplayList.add(String.format("%d", b.getBundleId()) + " " + b.getSymbolicName() + " " + OSGiFramework.describeState(b.getState()) + "\n");
					}
					
					//*************************************************
					//Add ApplicationContext as Service to the OSGi
					context.registerService(Context.class, HelloAndroidActivity.this.getApplicationContext(), new Hashtable<String, Object>());
				} 
		        catch (Exception e) {
					Log.w(TAG,e);
				}	
		        
		        tv.clearComposingText();
	         	for( String str : m_DisplayList){
			        tv.append(str);
	        	}	        
        }});
        
        Button btnStop = (Button) this.findViewById(R.id.btn_stop);
        btnStop.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				try {
					m_OSGiFramework.stop();
				} 
				catch (BundleException e) {
					Log.w(TAG,e);
				}
		}});
        
        Button btnService = (Button) this.findViewById(R.id.btn_service);
        btnService.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				//Get Services from BundleContext
				BundleContext context = m_OSGiFramework.getSystemContext();
				ServiceReference<?> ref = context.getServiceReference(IEventProxyService.class.getName());
		        if (ref != null){
		        	IEventProxyService eventProxy = (IEventProxyService) context.getService(ref);
		        	eventProxy.dispatch(new Report());
		        }			
        }});
        
        Button btnBroadcast = (Button) this.findViewById(R.id.btn_broascast);
        btnBroadcast.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				//Send a broadcaster
				Intent intent = new Intent();
				intent.setAction(Actions.ACTION_LOCATION_CHANGED);
				intent.putExtra("HighScore", 1000);
				sendBroadcast(intent);
        }});     
        
        if (savedInstanceState != null) {
        	m_DisplayList = savedInstanceState.getStringArrayList(KEY_BUNDLES_VALUE);
	        tv.clearComposingText();
        	for( String str : m_DisplayList){
		        tv.append(str);
        	}
        }
        else {
	        tv.clearComposingText();
           	for( String str : m_DisplayList){
		        tv.append(str);
        	}
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Inflate the menu; this adds items to the action bar if it is present.
    	getMenuInflater().inflate(R.menu.main, menu);
    	return true;
    }
    
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putStringArrayList(KEY_BUNDLES_VALUE, m_DisplayList);
    }

}

